<?php
/* ******************************
PHP Guest Book.
Wrtten by Alexander Leutch <alexander.leitch@gmail.com>

Description:
This is a basic guest book that does not use a database,
a text file is used with values sepeerated by new lines 
and the ;

Details:
Email is validated. Name and message are check for values.
 

****************************** */

class guestbook {
	
	var $name ;
	var $email ;
	var $message ;
	var $guestLog ;
	var $handle ;
	var $filename ;
	var $errors ;
	
	function guestbook(){
		$this->errors = array();
		$this->setName($_POST['name']);
		$this->setEmail($_POST['email']);
		$this->setMessage($_POST['message']);
	}
	
	function init(){
		
		// Open data file
		if (!$this->handle = fopen($this->filename, 'r')) {
			echo "Cannot open file ($this->filename)";
		}
		
		if( $_POST['phpaction'] == "true" ){
			// validate guestbook entry.
			if(is_writable($this->filename) ){
				$this->errors = $this->validate();
				if( empty($this->errors) ){
					$this->writeNew();
				} else {
//					echo "Data Not valid.";
				}
			} else {
//				echo "File note writable!";
			}
		}
		$this->populateObj();
		
		fclose($this->handle);
		
	}
	
	function validate(){
		
		$errors = array();
		
		if ( empty( $this->name ) ){
			$errors['name'] = "Please enter your name.." ;
		}
			
		if ( !ereg('^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$', $this->email ) ){
			$errors['email'] = "Please enter a valid email address.";
		}
		
		if ( empty( $this->email ) ){
			$errors['email'] = "Please enter your email address.";
		}
		
		if ( empty( $this->message ) ){
			$errors['message'] = "Please enter a message.";
		}
			
		return $errors;
	}
	
	function writeNew(){
		
		$content = "".$this->name .";".$this->email.";".$this->message.";".date("Y-m-d h:m:s").";\n";
		$handle = fopen($this->filename, 'a');
		
		// Write $somecontent to our opened file.
	    if (fwrite($handle, $content) === FALSE) {
	        echo "Cannot write to file ($this->filename)";
	        exit;
	    }

	    fclose($handle);
		//echo "Success, wrote ($this->name) to file ($this->filename)";
	}
	
	function populateObj(){
		
		$handle = fopen($this->filename, "r");
		$contents = fread($handle, filesize($this->filename));
		fclose($handle);
		$book = array();
		$contents = split(";\n", $contents);
		
		foreach($contents as $content){
			if($content != ""){
				$content = split(";", $content );
				array_push($book,  $content) ;
			}
		}
		
		$this->setBook($book);
	}
	
	function setFilename($filename){
		$this->filename = $filename;
	}
	
	function setBook($guestLog){
		$this->guestLog = $guestLog ;
	}
	
	function getBook(){
		return $this->guestLog ;
	}
	
	function setName($name){
//		echo "Setting name: ".$name."<br>\n";
		$this->name = $name;
	}
	
	function setEmail($email){
//		echo "Setting Email: ".$email."<br>\n";
		$this->email = $email;
	}
	
	function setMessage($message){
//		echo "setting message: ".$message."<br>\n";
		$this->message = $message;
	}
	
}
?>